package com.atguigu.educenter.controller;

import com.atguigu.commonutils.HttpClientUtils;
import com.atguigu.commonutils.JwtUtils;
import com.atguigu.educenter.entity.UcenterMember;
import com.atguigu.educenter.service.UcenterMemberService;
import com.atguigu.educenter.utils.WxProperties;
import com.atguigu.commonutils.ResponseEnum;
import com.atguigu.servicebase.exception.BusinessException;
import com.google.gson.Gson;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;


/**
 * @descriptions:
 * @author: pandengZhu
 * @date: 2024/4/13 11:52
 * @version: 1.0
 */

@Controller
//@CrossOrigin
@RequestMapping("/api/ucenter/wx")
public class WxController {

    @Resource
    private UcenterMemberService memberService;


    /**
     * 回调接口
     *
     * @param code
     * @param state
     * @return
     */
    @GetMapping("/callback")
    public String callback(String code, String state) {

        try {
            //1 获取code值，临时票据，类似于验证码
            //2 拿着code请求 微信固定的地址，得到两个值 accsess_token 和 openid
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token"
                    + "?appid=%s"
                    + "&secret=%s"
                    + "&code=%s"
                    + "&grant_type=authorization_code";

            //拼接三个参数 ： baseAccessTokenUrl，  id，  秘钥 和 code值
            String accessTokenUrl = String.format(baseAccessTokenUrl,
                    WxProperties.WX_OPEN_APP_ID,
                    WxProperties.WX_OPEN_APP_SECRET,
                    code);
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);

            //从accessTokenInfo字符串获取出来两个值 accsess_token 和 openid
            //把accessTokenInfo字符串转换map集合，根据map里面key获取对应值
            //使用json转换工具 Gson
            Gson gson = new Gson();
            HashMap hashMap = gson.fromJson(accessTokenInfo, HashMap.class);
            String accessToken = (String) hashMap.get("access_token");
            String openid = (String) hashMap.get("openid");

            //把扫描人信息添加数据库里面
            //判断数据表里面是否存在相同微信信息，根据openid判断
            UcenterMember member = memberService.getOpenIdMember(openid);
            //memeber是空，表没有相同微信数据，进行添加会员
            //Assert.isNull(member, ResponseEnum.ADD_UCENTER_MEMBER);
            if (member == null) {
                //3 拿着得到accsess_token 和 openid，再去请求微信提供固定的地址，获取到扫描人信息
                //访问微信的资源服务器，获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com//sns/userinfo" +
                        "?access_token=%S" +
                        "&openid=%s";
                //拼接两个参数
                String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openid);

                //发送请求
                String userInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println(userInfo);
                //获取返回userinfo字符串扫描人信息

                HashMap map = gson.fromJson(userInfo, HashMap.class);
                String nickname = (String) map.get("nickname");
                String headimgurl = (String) map.get("headimgurl");

                member = new UcenterMember();
                member.setNickname(nickname);
                member.setAvatar(headimgurl);
                member.setOpenid(openid);
                memberService.save(member);
            }
            //使用jwt根据member对象生成token字符串
            //String token = JwtUtil.createToken(member.getId(), member.getNickname());
            String token = JwtUtils.getJwtToken(member.getId(), member.getNickname());
            return "redirect:http://localhost:3000?token=" + token;
        } catch (Exception e) {
            throw new BusinessException(ResponseEnum.ERROR.getCode(),ResponseEnum.ERROR.getMessage());
        }


    }

    /**
     * 生成微信扫描二维码
     *
     * @return
     */
    @GetMapping("/login")
    public String wxLogin() {

        // 微信开放平台授权baseUrl
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect?" +
                "appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect ";

        //获取业务服务器重定向地址
        String redirectUrl = WxProperties.WX_OPEN_REDIRECT_URL;

        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new BusinessException(20001, e.getMessage());
        }
        String url = String.format(baseUrl, WxProperties.WX_OPEN_APP_ID, redirectUrl, "atguigu");

        return "redirect:" + url;
    }

}
